package cn.benben.web.exception;


import cn.benben.core.exception.AjaxResult;
import cn.benben.core.exception.BaseException;
import cn.benben.core.utils.StringUtils;
import org.apache.dubbo.rpc.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;


/**
 * 全局异常处理器
 *
 * @author xn
 */
@RestControllerAdvice
public class GlobalExceptionHandler
{
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);



    /**
     * 业务异常
     */
    @ExceptionHandler(cn.benben.web.exception.ServiceException.class)
    public AjaxResult businessException(cn.benben.web.exception.ServiceException e)
    {
        if (StringUtils.isNull(e.getCode()))
        {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.error(e.getCode(), e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("系统异常", e);
        String code = null;
        if (e instanceof BaseException) {
            code = ((BaseException)e).getCode();
        }
        return code != null ? AjaxResult.error(code, "系统异常") : AjaxResult.error("系统异常");
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("系统异常", e);
        return AjaxResult.error("系统异常");
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(RpcException.class)
    public AjaxResult validatedBindException(RpcException e)
    {
        log.error(e.getMessage(), e);
        String message = e.getMessage();
        return AjaxResult.error(message);
    }




}
